package org.footballmanager.pandafootball.system.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.common.util.DateUtils;
import org.footballmanager.pandafootball.system.dao.FootMissionDao;
import org.footballmanager.pandafootball.system.domain.FootMission;
import org.footballmanager.pandafootball.system.domain.FootSj;
import org.footballmanager.pandafootball.system.domain.FootUser;
import org.footballmanager.pandafootball.system.domain.enums.SJZT;
import org.footballmanager.pandafootball.system.form.impl.FootMissionSearchForm;
import org.footballmanager.pandafootball.system.mapper.FootMissionMapper;
import org.footballmanager.pandafootball.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Slf4j
@Service("footMissionService")
public class FootMissionServiceImpl extends ServiceImpl<FootMission> implements FootMissionService {
    private static final String MISSIONNAME = "missionName";
    @Autowired
    private FootMissionDao footMissionDao;
    @Autowired
    private FootMissionMapper footMissionMapper;
    @Autowired
    private FootMissionHistoryService footMissionHistoryService;
    @Autowired
    private FootBfinfoService footBfinfoService;
    @Autowired
    private FootUserService footUserService;
    @Autowired
    private FootZjService footZjService;
    @Autowired
    private FootSjService footSjService;

    /**
     * 结束所有任务，并添加新任务
     *
     * @param sjzt    赛季状态
     * @param request 请求
     */
    @Override
    public void addNewMission(SJZT sjzt, HttpServletRequest request) {
        footMissionHistoryService.processHistoryRecord(request);
        List<FootUser> list = footUserService.findGameIdIsNotNull();
        for (FootUser user : list) {
            saveNewMissionToTable(user, sjzt, request);
        }
    }

    /**
     * 保存新的任务
     *
     * @param user    用户实体类
     * @param sjzt    赛季状态
     * @param request 请求
     */
    private void saveNewMissionToTable(FootUser user, SJZT sjzt, HttpServletRequest request) {
        if (user.getJoins()) {
            if (sjzt.equals(SJZT.NORMAL)) {
                saveNewMission("每日常规赛任务", "每天进行1场常规赛，完成即可领取奖励5PB", 1, user, request);
            } else {
                saveNewMission("每日排位赛任务", "每天进行2场排位赛，完成即可领取奖励5PB", 2, user, request);
            }
            saveNewMission("每日热身赛任务", "每天进行2场热身赛，完成即可领取奖励5PB", 2, user, request);
        }
    }

    /**
     * 保存新任务
     *
     * @param missionName   任务名称
     * @param missionDetail 任务描述
     * @param num           数量
     * @param user          用户
     * @param request       请求
     */
    private void saveNewMission(String missionName, String missionDetail, Integer num,
                                FootUser user, HttpServletRequest request) {
        FootMission mission = new FootMission();
        mission.setComplete(false);
        mission.setMissionName(missionName);
        mission.setMissionNum(num);
        mission.setMissionDetail(missionDetail);
        mission.setUserId(user.getId());
        this.save(mission, request);
    }

    /**
     * 根据玩家主键结束对应任务
     *
     * @param userId   用户主键
     * @param isReshen 是否是热身赛
     * @param request  请求
     */
    @Override
    public void finishMission(Long userId, boolean isReshen, HttpServletRequest request) {
        FootMission mission;
        if (isReshen) {
            mission = findMissionByUserIdandStatus(userId, null);
        } else {
            FootSj sj = footSjService.get(footSjService.getSj());
            mission = findMissionByUserIdandStatus(userId, sj.getSjzt());
        }
        if (null != mission) {
            mission.setMissionNum(mission.getMissionNum() - 1);
            this.updateNotNull(mission, request);
        }
    }

    /**
     * 根据玩家和时间找对应任务
     *
     * @param userId 用户主键
     * @param sjzt   赛季状态
     * @return 任务记录
     */
    @Override
    public FootMission findMissionByUserIdandStatus(Long userId, SJZT sjzt) {
        Example example = new Example(FootMission.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(Constants.USERID, userId);
        Date date = new Date();
        criteria.andBetween("createTime", DateUtils.processWithStartOrEnd(date, true), DateUtils.processWithStartOrEnd(date, false));
        if (null != sjzt) {
            if (sjzt.equals(SJZT.NORMAL)) {
                criteria.andLike(MISSIONNAME, "%常规赛%");
            } else {
                criteria.andLike(MISSIONNAME, "%排位赛%");
            }
        } else {
            criteria.andLike(MISSIONNAME, "%热身赛%");
        }
        criteria.andEqualTo("delFlag", 0);
        return this.findByExample(example);
    }

    /**
     * 根据玩家找所有对应任务
     *
     * @param userId 用户主键
     * @return 任务列表
     */
    @Override
    public List<FootMission> findMissionsByUserId(Long userId) {
        Example example = new Example(FootMission.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(Constants.USERID, userId);
        criteria.andEqualTo("delFlag", 0);
        return this.findall(example);
    }

    /**
     * 领取任务奖励
     *
     * @param userId   用户主键
     * @param isReshen 是否是热身赛
     * @param request  请求
     */
    @Override
    public void getMissionMoney(Long userId, boolean isReshen, HttpServletRequest request) {
        FootMission mission;
        int missionnum;
        if (isReshen) {
            missionnum = footBfinfoService.countMissionNumByUserId(userId, 2);
            mission = findMissionByUserIdandStatus(userId, null);
        } else {
            missionnum = footBfinfoService.countMissionNumByUserId(userId, 1);
            FootSj sj = footSjService.get(footSjService.getSj());
            mission = findMissionByUserIdandStatus(userId, sj.getSjzt());
        }
        if (null != mission && !mission.getComplete() && mission.getMissionNum() <= missionnum) {
            mission.setComplete(true);
            this.updateNotNull(mission, request);
            footZjService.getMissionMoney(userId, 5D, isReshen, request);
        }
    }

    /**
     * 翻页方法
     *
     * @param footMissionSearchForm 条件
     * @return 列表
     */
    @Override
    public List<FootMission> findall(FootMissionSearchForm footMissionSearchForm) {
        return footMissionMapper.findall(footMissionSearchForm);
    }

    /**
     * 根据主键获取记录
     *
     * @param id 主键
     * @return 记录
     */
    @Override
    public FootMission get(Serializable id) {
        return footMissionMapper.findById(id);
    }

    /**
     * 查询
     *
     * @param entityname            实体类名
     * @param map                   参数
     * @param footMissionSearchForm 条件
     */
    @Override
    public void search(String entityname, Model map, FootMissionSearchForm footMissionSearchForm) {
        map.addAttribute(String.format(Constants.FORMNAME, entityname), footMissionSearchForm);
        Page<FootMission> page = PageHelper.startPage(footMissionSearchForm.getPageIndex(), footMissionSearchForm.getPageSize());
        List<FootMission> list = this.findall(footMissionSearchForm);
        map.addAttribute(Constants.PI, page.toPageInfo());
        map.addAttribute(String.format(Constants.LISTENTITY, entityname), list);
    }

    /**
     * 真实删除数据
     *
     * @param id 主键
     */
    @Override
    public void deleteNotLogic(Long id) {
        footMissionDao.deleteByPrimaryKey(id);
    }

    /**
     * 根据用户主键删除相关记录
     *
     * @param userId  用户主键
     * @param request 请求
     */
    @Override
    public void deleteByUserId(Long userId, HttpServletRequest request) {
        FootMissionSearchForm footMissionSearchForm = new FootMissionSearchForm();
        footMissionSearchForm.setUserId(userId);
        List<FootMission> list = this.findall(footMissionSearchForm);
        if (list != null && !list.isEmpty()) {
            for (FootMission footMission : list) {
                this.deleteNotLogic(footMission.getId());
            }
        }
    }
}
